import { PageContainer } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  TimePicker,
  DatePicker,
  Popover,
  Checkbox,
  Space,
} from "antd";
import { connect } from "umi";
import { useEffect, useRef, useState } from "react";
import WeekTable from "@/components/WeekTable";
import styles from "./style.less";
const { RangePicker } = DatePicker;
import { getUrlParam } from "@/utils/utils";
import { namespace } from "./configFile";
import dayjs from "dayjs";

const Page = (props) => {
  const { dispatch, submitLoading } = props;
  const [open, setOpen] = useState(false);
  const [titleType, setTitleType] = useState(0);
  const [form] = Form.useForm();

  const [staff, setStaff] = useState({});
  const [week, setWeek] = useState(0);
  const [dayOff, setDaff] = useState([]);

  useEffect(() => {
    let userId = getUrlParam("id");
    dispatch({
      type: `${namespace}/pageInit`,
      params: {
        userId,
        week,
      },
      callback: (res, staff, venues) => {
        if (staff && staff.code === 200) {
          if (staff.rows.length) {
            let venue = venues.filter((v) => v.id == staff.rows[0].venueId);
            setStaff({
              ...staff.rows[0],
              venueName: venue.length ? venue[0].venueName : "",
            });
          }
        }
        setDaff(res);
      },
    });
  }, []);

  const queryData = async () => {
    dispatch({
      type: `${namespace}/queryTable`,
      params: {
        userId: staff.userId,
        week,
      },
      callback: (res) => {
        setDaff(res);
      },
    });
  };

  const deleteItem = async (params) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params,
      callback: () => {
        queryData();
      },
    });
  };

  const submitForm = async () => {
    let res = await form.validateFields();
    if (res) {
      if (titleType !== 2) {
        res.startTime = dayjs(res.startTime).format("YYYY-MM-DD HH:mm:ss");
        res.endTime = dayjs(res.endTime).format("YYYY-MM-DD HH:mm:ss");
      }
      if (res.circleTime) {
        if (titleType === 2) {
          res.startTime = `${res.data} ${dayjs(res.circleTime[0]).format(
            "HH:mm"
          )}:00`;
          res.endTime = `${res.data} ${dayjs(res.circleTime[1]).format(
            "HH:mm"
          )}:00`;
          delete res.data;
        } else {
          res.circleStartTime = dayjs(res.circleTime[0]).format("HH:mm:ss");
          res.circleEndTime = dayjs(res.circleTime[1]).format("HH:mm:ss");
        }
        delete res.circleTime;
      }
      if (res.days) {
        res.days = res.days.toString();
        if (res.circleStartTime && res.circleEndTime) {
          res.circleFlag = "0";
        }
      }
      dispatch({
        type: `${namespace}/submitItem`,
        params: {
          ...res,
          holidayType: "3",
        },
        callback: () => {
          setOpen(false);
          queryData();
        },
      });
    }
  };
  return (
    <PageContainer
    // extra={
    //   <Button
    //     type='primary'
    //     onClick={() => {
    //       let {venueId,userId} = staff
    //       form.resetFields()
    //       form.setFieldsValue({
    //         venueId,
    //         staffId:userId,
    //       })
    //       setTitleType(0)
    //       setOpen(true)
    //     }}
    //   >
    //     休息设置
    //   </Button>
    // }
    >
      <WeekTable
        title={`${staff?.nickName} (${staff?.venueName})`}
        cellItem={<div>item</div>}
        nickName={staff?.nickName}
        deleteItem={(data) => {
          deleteItem({ holidayId: data.id });
        }}
        editInfo={(data) => {
          let { id, staffId, startTime, endTime, venueId } = data;
          console.log(dayjs(startTime).format("YYYY-MM-DD"));
          form.setFieldsValue({
            id,
            staffId,
            venueId,
            data: dayjs(startTime).format("YYYY-MM-DD"),
            circleTime: [dayjs(startTime), dayjs(endTime)],
          });
          setTitleType(2);
          setOpen(true);
        }}
        onPreWeek={() => {
          setWeek(week - 1);
          queryData();
        }}
        onNextWeek={() => {
          setWeek(week - 1);
          queryData();
        }}
        onAddClick={(value) => {
          let { venueId, userId } = staff;
          form.resetFields();
          form.setFieldsValue({
            venueId,
            staffId: userId,
            data: value,
          });
          setTitleType(2);
          setOpen(true);
        }}
        dayOff={dayOff}
      />

      <Modal
        open={open}
        title={titleType === 1 ? "员工休息编辑" : "员工休息设置"}
        forceRender
        onCancel={() => setOpen(!open)}
        footer={
          <Space>
            <Button onClick={() => setOpen(false)}>取消</Button>
            <Button onClick={submitForm} loading={submitLoading} type="primary">
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item label="所属场馆" name="venueId">
            {staff.venueName}
          </Form.Item>
          <Form.Item
            label="员工昵称"
            name="staffId"
            // rules={[{required: true, message: '用户名称不能为空'}]}
          >
            {staff.nickName}
          </Form.Item>

          {titleType === 2 && (
            <Form.Item label="休息日期" name="data">
              {form.getFieldValue("data")}
            </Form.Item>
          )}
          {titleType !== 2 && (
            <Form.Item
              label="开始日期"
              name="startTime"
              rules={[{ required: true, message: "开始日期不能为空" }]}
            >
              <DatePicker showTime />
            </Form.Item>
          )}

          {titleType !== 2 && (
            <Form.Item
              label="结束日期"
              name="endTime"
              rules={[{ required: true, message: "结束日期不能为空" }]}
            >
              <DatePicker showTime />
            </Form.Item>
          )}

          {titleType === 0 && (
            <Form.Item label="星期设置" name="days">
              <Checkbox.Group>
                <Checkbox value={1}>周一</Checkbox>
                <Checkbox value={2}>周二</Checkbox>
                <Checkbox value={3}>周三</Checkbox>
                <Checkbox value={4}>周四</Checkbox>
                <Checkbox value={5}>周五</Checkbox>
                <Checkbox value={6}>周六</Checkbox>
                <Checkbox value={7}>周日</Checkbox>
              </Checkbox.Group>
            </Form.Item>
          )}
          {titleType !== 1 && (
            <Form.Item
              label="休息时间"
              name="circleTime"
              rules={
                titleType === 2
                  ? [{ required: true, message: "休息时间不能为空" }]
                  : false
              }
            >
              <TimePicker.RangePicker minuteStep={15} format={"HH:mm"} />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state,
}))(Page);
